const mqtt = require("mqtt");
const { insertCO2Data } = require("./data_co2.js");
const { insertTempData } = require("./data_temperature.js");
const { insertHumidtyData } = require("./data_humidty.js");

const client = mqtt.connect({
  host: "111.229.163.181",
  port: 1883,
});

client.on("connect", () => {
  client.subscribe("application/1/device/+/rx", (err, granted) => {
    if (err) {
      console.error("数据源错误");
      console.log(`错误信息=> ${err}`);
    }
  });
});

client.on("message", function (topic, message) {
  const deveui = topic.split("/");
  console.log(`<----topic---->`);
  console.log(deveui);
  console.log(`<----topic---->`);
  //1.字符串 转 JSON 对象
  const data_json_format = JSON.parse(message.toString());
  //2.JSON.data base64解码 转Buffer对象
  let buffer = Buffer.from(data_json_format.data, "base64");
  //3. Buffer对象，掐头（4个元素）去尾（2个元素） 保留最终有效数据
  let buffer_valid = Uint8Array.prototype.slice
    .call(buffer)
    .slice(4, buffer.length - 2);
  console.log(`<----buffer_valid---->`);
  console.log(`${buffer_valid}`);
  console.log(`<----buffer_valid---->`);
  filterData(deveui[3], buffer_valid);
});

function filterData(deveui, message) {
  console.log(`<--- ${deveui} --->`);
  switch (deveui) {
    case "8D00003100000005":
      console.log(`<--- switch to 05 --->`);
      handle05Data(deveui, message);
      break;
    case "8D00003100000006":
      console.log(`<--- switch to 06 --->`);
      handle06Data(deveui, message);
      break;
    case "8D00003100000007":
      console.log(`<--- switch to 07 --->`);
      handle07Data(deveui, message);
      break;
    case "8D00003100000008":
      console.log(`<--- switch to 08 --->`);
      handle08Data(deveui, message);
      break;
    case "8d00000051040013":
      console.log(`<--- switch to 13 --->`);
      handle13Data(deveui, message);
      break;
    default:
      break;
  }
}

function handle05Data(deveui, message) {}
function handle06Data(deveui, message) {}
function handle07Data(deveui, message) {}
function handle08Data(deveui, message) {}
function handle13Data(deveui, message) {
  //4. 插入Co2数据
  insertCO2Data(deveui, message);
  //5. 插入温度数据
  insertTempData(deveui, message);
  //6. 插入湿度数据
  insertHumidtyData(deveui, message);
}
